<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 蔻丁同学
  Date: 2017/4/3
  Time: 11:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>商品管理</title>
    <link href="${ctx}/resources/pagination/style/pagination.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/resources/pagination/style/common.css" rel="stylesheet" type="text/css">
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/cloud-head.jsp"></jsp:include>
    <jsp:include page="../../common/dt.jsp"></jsp:include>
    <script type="text/javascript" src="${ctx}/resources/pagination/script/jquery.pagination.js"></script>
    <style>
        table img.data-preview-img.edit_able {
            margin: 0.2rem 0.4rem;
            width: 8rem;
        }

        .upload-img-box {
            width: 24%;
            margin: 0 1rem;
            vertical-align: center;
            display: inline-block;
        }

        #addDialog {
            width: 800px;
            height: 480px;
            background: transparent;
            box-shadow: none;
            height: auto;
            padding: 0;
            overflow: visible;
        }

        #addDialog .modal-dialog {
            width: 100%;
            height: 100%;
            overflow: hidden;
            padding: 0;
            margin: 0;
        }

        #addDialog .modal-content {
            padding: 0;
        }

        #addDialog .modal-body {
            height: 380px;
            overflow-y: auto;
        }

        #picBox .form-group {
            margin: 0;
            padding: 0;
        }

        .modal .modal-footer .btn, .modal .modal-footer .btn-large, .modal .modal-footer .btn-flat {
            float: none;
        }

        .good-class-box {
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 0.4rem 0.8rem;
            box-shadow: -2px 2px 5px #ccc inset;
            max-height: 200px;
            overflow-y: auto;
        }

        .form-group {
            margin: 0 auto !important;
        }

        .size-box {
            text-align: left;
        }

        .size-box input {
            width: 20% !important;
            display: inline-block;
            vertical-align: middle;
            float: none;
        }

        .modal-header .close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            color: #505e5f;
            opacity: 1;
        }

        .data-preview-img {
            width: 23%;
            vertical-align: top;
            margin: 0 1%;
        }

        #mainTable .form-group {
            min-width: 20rem;
            font-size: 12px;
            color: #333;
            line-height: 1.8rem;
        }

        .status-active, .status-disabled {
            font-size: 12px;
            font-family: "Microsoft YaHei";
            color: #0aa;
        }

        .status-disabled {
            color: #a33;
        }

        . sorting_1 {
            background: none;
        }

        span.edit_able {
            cursor: pointer;
            position: relative;
            border-bottom: 1px solid transparent;
        }

        span.edit_able:hover {
            border-bottom-color: #8c8c8c;

        }

        span.edit_able:hover:after {
            content: '\f044';
            font-family: FontAwesome;
            margin-left: 0.5rem;
            color: #0aa;
            text-decoration: none !important;

        }

        td:first-child {
            width: 41rem !important;
        }

        .img-box {
            display: inline-block;
            width: 19rem;
            vertical-align: top;
            border-right: 1px solid #afafaf;
        }

        .good-info-box {
            display: block;
            vertical-align: top;
        }

        .gc-box label {
            display: block !important;
        }

        .gc-box span {
            border: 1px solid #0aa;
            padding: 0.1rem 0.6rem;
            border-radius: 3px;
            background: rgba(0, 130, 199, .6);
            color: #fff;
        }

        #mainTable label.control-label.col-md-3 {
            min-width: 8rem;
        }

        .nav {
            position: static;
            background-color: transparent;
            height: auto;
        }

        .chosen-drop {
            z-index: 12001 !important;
        }

        .addPriceItem {
            width: 50%;
            height: 45px;
            float: left;
        }
        #dele-btn{
            margin-top: 10px;
        }

    </style>
</head>
<body>
<div class="col-md-12">
    <div class="card">
        <div class="card-action">
            条件查询
            <%--<shiro:hasAnyRoles name="GOOD_MGR">--%>
            <button class="btn btn-primary" id="addBtn"><i class="fa fa-plus"></i>添加商品</button>
            <%--</shiro:hasAnyRoles>--%>
            <button class="btn btn-primary" onclick="loadData();"><i class="fa fa-search"></i>查询</button>
        </div>
        <div class="card-content">
            <input type="hidden" value="1" name="pageNum" id="pageNum"/>
            <input type="hidden" value="5" name="pageSize" id="pageSize"/>
            <input type="hidden" value="" name="total" id="total"/>
            <div class="form-group normal col-md-3">
                <label>商品名称:</label>
                <input type="text" value="" id="goodName" name="goodName"/>
            </div>
            <shiro:hasAnyRoles name="all">
                <div class="form-group normal col-md-3">
                    <label>商家</label>
                    <select id="wx_user_id" name="wx_user_id" style="max-width:15rem;">
                        <option value="" selected>全部</option>
                        <c:forEach items="${shopUsers}" var="sp">
                            <option value="${sp.id}">${sp.companyName}</option>
                        </c:forEach>
                    </select>
                </div>
            </shiro:hasAnyRoles>
            <div class="form-group normal col-md-3">
                <label>状态</label>
                <select id="status" name="status" style="max-width:15rem;">
                    <option value="">全部</option>
                    <option value="1">已上架</option>
                    <option value="0">已下架</option>
                </select>
            </div>
            <div class="form-group normal col-md-3">
                <label>商品类型</label>
                <select name="qbigType" id="qbigType" style="width:14rem;display:inline-block;">
                    <option value="">全部</option>
                    <option value="新品">新品</option>
                    <option value="二手">二手</option>
                    <option value="配件">配件</option>
                </select>
            </div>
            <div class="clear"></div>
        </div>
    </div>
</div>
<div class="col-md-12">
    <div class="card">
        <div class="card-content">
            <table id="mainTable" cellpadding="0" cellspacing="0" border="0" class="auto-table">
                <thead>
                <tr>
                    <th>商品基础信息</th>
                    <th>厂家/规格</th>
                    <th>状态</th>
                    <th>库存</th>
                    <th>商品类型</th>
                    <shiro:hasRole name="all">
                        <th>商家名称</th>
                    </shiro:hasRole>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
            <div class="pagination pagination-right pagination-small" id="pagination">

            </div>
        </div>
    </div>
</div>
<%--<jsp:include page="content/good-add1.jsp"></jsp:include>--%>
<%--2018.1.13--%>
<jsp:include page="content/good-add.jsp"></jsp:include>
<jsp:include page="content/good-tmpl.jsp"></jsp:include>
<jsp:include page="content/common-tmpl.jsp"></jsp:include>


<script src="${ctx}/resources/script/common.js" type="text/javascript"></script>
<script>
    var addFormHtml = $("#addForm").html();
    $(function () {
        $("#wx_user_id").chosen();

        $("#productTime").datetimepicker({
            format: "yyyy-mm-dd hh:ii:ss",
            autoclose: true,
            todayBtn: true
        });
        loadData();
        loadExpressData();
        handlerGoodClassTree();
        $("#addBtn").click(function () {
            FormWizard.init({
                target: "addForm",
                confirm: function () {

                    var goodClass = $('#goodClassTree').tree('selectedItems');
                    var goodExpress = $('#goodExpress').val();
                    var goodExpressText = "";
                    $("#goodExpress option:selected").each(function () {
                        goodExpressText += "," + $(this).text();
                    });
                    //console.log("good express text:%o", goodExpressText);
                    //console.log("good express:%o", goodExpress);
                    //console.log("good classes:%o", goodClass);
                    var gcs = [];
                    var gcids = [];
                    $.each(goodClass, function (gid, gc) {
                        gcs.push(gc.name);
                        gcids.push(gc.id);
                    })
                    if (isEmpty(gcids)) {
                        bootbox.alert("请选择商品类别！");
                        $("#addForm .prevBtn").click();
                        return -1;
                    }
                    if (isEmpty(goodExpress)) {
                        bootbox.alert("请选择商品物流！");
                        $("#addForm .prevBtn").click();
                        return -1;
                    }

//                    bootbox.alert("正在校验表单！");
                    $("*[data-display]").each(function () {
                        var _this = $(this);
                        _this.html("");
                        var targetIds = $(this).attr("data-display");
                        var targetType = $(this).attr("data-type");
                        var targetSplit = isEmpty($(this).attr("data-split")) ? " " : $(this).attr("data-split");
                        if (!isEmpty(targetIds)) {
                            var targetIdArray = targetIds.split(",");
                            var contentText = "";
                            $.each(targetIdArray, function (index, targetId) {
                                if (targetType == "img") {
                                    var src = isEmpty($("#" + targetId).attr("src")) ? $("#" + targetId).val() : $("#" + targetId).attr("src");
                                    if (!isEmpty(src)) {
                                        _this.append("<img class=\"data-preview-img\" src=\"" + src + "\"/>");
                                    } else {
                                        _this.append("<span style=\"margin:0 1%;display:block;\">" + targetId + "无图片</span>")
                                    }
                                } else {
                                    var value = $("#" + targetId).val();
                                    if (!isEmpty(value)) {
                                        if (!isEmpty(contentText)) {
                                            contentText += targetSplit;
                                        }
                                        contentText += value;
                                    } else {
                                        contentText += "无"
                                    }
                                }
                            })
                            if (!isEmpty(contentText)) {
                                _this.text(contentText);
                            }
                        }
                    })

                    var content = ue.getContent();
                    $("#confirmContent").html(content);

                    $("#goodClass").val(gcids);
                    $("#confirmGoodExpress").text(goodExpressText);
                    $("#confirmGoodClass").text(gcs.toString());
                },
                submit: function () {
                    var colorPricesArray = [];
                    var sizePricesArray = [];
                    $("div .addColorPriceItem").each(function () {
                        var _this = $(this);
                        var colorPrice = {
                            color: _this.find("input[name='inputColor']").val(),
                            price: _this.find("input[name='inputColorPrice']").val()
                        }

                        colorPricesArray.push(colorPrice);

                    })

                    var colorPrices = {colorPrices: colorPricesArray};

                    $("div .addSizePriceItem").each(function () {
                        var _this = $(this);
                        var sizePrice = {
                            color: _this.find("input[name='inputSize']").val(),
                            price: _this.find("input[name='inputSizePrice']").val()
                        }

                        sizePricesArray.push(sizePrice);

                    })

                    var sizePrices = {sizePrices: sizePricesArray};

                    var data = $("#addForm").serializeJson()
                    if (colorPricesArray.length > 0) {
                        delete data.inputColor;
                        delete data.inputColorPrice;
                    }

                    if (sizePricesArray.length > 0) {
                        delete data.inputSize;
                        delete data.inputSizePrice;
                    }

                    var dataArry = $("#addForm").serializeArray();
                    var goodClass = $('#goodClassTree').tree('selectedItems');
                    data["good_class_id"] = goodClass[0]["id"] + "";
                    data["good_class_name"] = goodClass[0]["name"].trim();
                    data["good_express"] = $('#goodExpress').val();

                    var lastdata = $.extend(data, colorPrices, sizePrices);

                    //console.log("商品信息:%o", lastdata);
//                    alert(data);

                    asyncAjax({
                        url: ctx + "/goodMgr/good/add",
                        data: JSON.stringify(lastdata),
                        type: "post",
                        dataType: "json",
                        contentType: "application/json;charset:UTF-8",
                        success: function (res) {
                            if (res.result == "0") {
                                $('#addDialog').modal('hide');
                                $("#addForm")[0].reset();
                                $("#addForm img").attr("src", "${ctx}/resources/ueditor/dialogs/image/images/image.png");
                                ue.setContent("");
                                $("#addForm input").val("");
                                $("#addForm .form-control-static,#confirmContent").html("");
                                $("#modal-header li.done").removeClass("done");
                                $('.nextBtn').show().removeClass("disabled");
                                $(".steps>li:eq(0)>a").click();
                                $(".wizard-form tab-pane:eq(0),.wizard-form tab-pane.active").toggleClass("active");
                                $(".addColorPriceItem").remove();
                                $(".addSizePriceItem").remove();
                                loadData();
                            } else {
                                bootbox.alert("发生错误" + res.msg);
                            }
                        }
                    })

                }
            });
            $("#addForm")[0].reset();
            $('#addDialog').modal('show');
        })
    })


    function pageLoad() {
        var pageCount = Math.ceil((parseInt(($('#total').val() || 0)) / parseInt($("#pageSize").val() || 10)));
        $("#pagination").pagination({
            pageCount: pageCount,
            pageSize: parseInt($("#pageSize").val() || 10),
            totalCount: parseInt($("#total").val()),
            current: parseInt($("#pageNum").val()),
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上页',
            nextContent: '下页',
            callback: function (that) {
                //console.log("that:%o", that);
                $("#pageNum").val(that.getCurrent());
                loadData();
                that.setCurrentPage()
            }
        })
    }

    var CURRENT_DATA_CACHE = {};

    function loadData() {
        CURRENT_DATA_CACHE = {};
        var data = {
            goodName: $("#goodName").val() || "",
            shopId: $("#wx_user_id").val() || "",
            status: $("#status").val() || "",
            pageNum: $("#pageNum").val() || "1",
            pageSize: $("#pageSize").val() || "10",
            bigType: $("#qbigType").val() || ""
        };
        asyncAjax({
            url: "${ctx}/goodMgr/good/list",
            data: data,
            beforeSend: function () {
                $("#mainTable tbody").html("<td colspan='" + $("#mainTable thead th").length + "'><div class=\"alert alert-success\"><i class=\"fa fa-spin fa-spinner\"></i>请求数据中...</div></td>");
            },
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == 0) {
                    Messenger().run({
                        successMessage: '请求数据成功',
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.success();
                        }
                    });
                    if (isEmpty(res["data"]["goods"])) {
                        $("#mainTable tbody").html("<td colspan='" + $("#mainTable thead th").length + "'><div class=\"alert alert-warning\">没有找到符合条件的数据</div></td>");
                        return -1;
                    }
                    $("#mainTable tbody").html("");
                    $("#total").val(res["total"]);
                    $.each(res.data["goods"], function (idx, item) {
                        if (!item["img"] || item["img"].length < 4) {
                            if (!item["img"]) {
                                item["img"] = ["emptyImg.png", "emptyImg.png", "emptyImg.png", "emptyImg.png"];
                            } else {
                                var lostImgCount = 4 - item["img"].length;
                                for (var i = 0; i < lostImgCount; i++) {
                                    item["img"].push("emptyImg.png" + i);
                                }
                            }
                        }
                        CURRENT_DATA_CACHE[item["good_id"]] = item;
                    })

                    $("#tableTmpl").tmpl(res.data["goods"]).appendTo($("#mainTable tbody"));

                    <shiro:hasRole name="all">
                    $(".shop-user").each(function () {
                        getShopUserInfo($(this).attr("data-id"), $(this));
                    })
                    </shiro:hasRole>

                    window.initEdit()
                    pageLoad();
                } else {
                    Messenger().run({
                        errorMessage: '请求数据发生错误:' + res.msg,
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.error();
                        }
                    });
                }
            }
        })
    }


    function getShopUserInfo(id, el) {
        var data = {};
        asyncAjax({
            url: ctx + "/user/mgr/user/" + id + "?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            data: data,
            success: function (res) {
                //console.log("res:%o", res);
                if (res["data"] && res["result"] == "0") {
                    el.html(res["data"]["companyName"]);
                } else {
                    el.html("未找到商户信息!");
                }
            }
        })
    }

    function handlerGoodClassTree() {
        asyncAjax({
            url: "${ctx}/shop/good/type/data",
            type: "post",
            success: function (res) {
                if (res.result == 0) {
                    var allClass = res.data.list;
                    var treeData = {};
                    treeData[allClass["title"]] = getClassItemData(allClass);
                    var daso = new DataSourceTree({data: treeData});
                    //console.log("tree datasource :%o", daso);
                    $('#goodClassTree').admin_tree({
                        dataSource: daso,
                        multiSelect: false,
                        loadingHTML: '<div class="tree-loading"><i class="fa fa-spinner fa-2x fa-spin"></i>Loading...</div>',
                        'open-icon': 'fa-minus',
                        'close-icon': 'fa-plus',
                        'selectable': true,
                        'selected-icon': 'fa-check',
                        'unselected-icon': 'fa-times'
                    });
                    $('.tree').find('[class*="fa-"]').addClass("fa");
                } else {
                    Messenger().run({
                        errorMessage: '请求数据发生错误:' + res.msg,
                        showCloseButton: true,
                        action: function (opts) {
                            return opts.error();
                        }
                    });
                }
            }
        })
    }

    function getClassItemData(item) {
        var itemData = {
            name: item["title"],
            id: item["_id"],
            type: !isEmpty(item.children) ? "folder" : "item"
        }
        if (!isEmpty(item.children)) {
            itemData["additionalParameters"] = {
                "children": {}
            };
            $.each(item.children, function (idx, citem) {
                itemData["additionalParameters"]["children"][citem["title"]] = getClassItemData(citem);
            })
        }
        return itemData;
    }

    function loadExpressData() {
        var data = {
            keyword: "",
            area: "",
            shopId: parseInt("${$_LoginUser.id}")

        };
        asyncAjax({
            url: ctx + "/express/mgr/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("物流数据:%o", res);
                if (res["result"] == "0") {
                    $("#goodExpress").empty();
                    for (var i in res.data) {
                        var item = '<option value="' + res.data[i].express_id + '">' + res.data[i].name + '</option>';
                        $("#goodExpress").append(item);
                    }
                    $("#goodExpress").chosen({
                        width: "100%"
                    });
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }
</script>
</body>
</html>
